using Consul;
using FoodTraceabilitySet;
using J.FoodManageGet.Extensions;
using J.FoodRepository;
using MediatR;
using NLog.Web;
using SqlSugar;
using System.Reflection;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<ISqlSugarClient>(x =>
{
    return new SqlSugarScope(new ConnectionConfig()
    {
        ConnectionString = "uid=root;database=Catering;server=10.31.56.15;pwd=123456789;port=3306",
        DbType = DbType.MySql,
        IsAutoCloseConnection = true,//自动释放数据务，如果存在事务，在事务结束后释放
        InitKeyType = InitKeyType.Attribute //从实体特性中读取主键自增列信息
    });


});

//builder.Services.AddHttpContextAccessor();
////ע��SqlSugar��AddScoped
//builder.Services.AddScoped(sp => new SqlSugarDbcontext(
//    new SqlSugarClient(new ConnectionConfig()
//    {
//        ConnectionString = builder.Configuration.GetConnectionString("Connection"), //���ݿ����Ӵ�
//        DbType = DbType.SqlServer,      //���ݿ�����
//        IsAutoCloseConnection = true, //�Զ��ͷ�
//        MoreSettings = new ConnMoreSettings()
//        {
//            SqlServerCodeFirstNvarchar = true,//�����ַ���Ĭ��Nvarchar
//        }
//    },
//    db =>
//    {
//        db.Aop.OnLogExecuting = (sql, pars) =>
//        {
//            Console.WriteLine(sql);//����ִ��Sql���
//        };
//    }

//    )
//));

// Add services to the container.
///<summary>
///ע��consul����
///</summary>
static void RegisterConsul()
{
    var consulClient = new ConsulClient(p => { p.Address = new Uri($"http://10.31.56.23:8500"); });//请求注册的Consul地址（不动）
                                                                                                   //这里的这个ip就是本机的ip，这个端口8500这个是默认注册服务端口
    var httpCheck = new AgentServiceCheck()
    {
        DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册
        Interval = TimeSpan.FromSeconds(10),//间隔固定的时间访问一次，https://localhost:44308/api/Health
        HTTP = $"http://10.31.56.23:8811/WeatherForecast",//健康检查地址放（发布地址）WeatherForecast不要动就改ip加端口号
        Timeout = TimeSpan.FromSeconds(5)
    };

    var registration = new AgentServiceRegistration()
    {
        Checks = new[] { httpCheck },
        ID = Guid.NewGuid().ToString(),
        Name = "foods",//服务名称项目名称
        Address = " http://10.31.56.23:8811/swagger/index.html",//改成发布地址
        Port = 8811,//服务端口（）
    };
    consulClient.Agent.ServiceRegister(registration).Wait();//注册服务
                                                            //consulClient.Agent.ServiceDeregister(registration.ID).Wait();//registration.ID是guid
                                                            //当服务停止时需要取消服务注册，不然，下次启动服务时，会再注册一个服务。
                                                            //但是，如果该服务长期不启动，那consul会自动删除这个服务，大约2，3分钟就会删了
}
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(o =>
{
    string xml = AppContext.BaseDirectory + "J.FoodManageSet.xml";
    o.IncludeXmlComments(xml, true);
});

//�н���ģʽ
builder.Services.AddMediatR(Assembly.GetExecutingAssembly());
//ע��ִ���
builder.Services.RegisterServices();
//ע��AuToMapper
//����������Assembly���͵����� ��ʾAutoMapper������Щ���������������Ѱ�����м̳���Profile��������ļ�
//�ڵ�ǰ����������г�������ɨ��AutoMapper�����ļ�
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
// ����ȫ�ֹ�����
builder.Services.AddControllers(x => x.Filters.Add<MyExceptionFilter>());
// ע��Nlog��־
builder.Host.UseNLog();
var app = builder.Build();

// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
    app.UseSwagger();
    app.UseSwaggerUI();
//}

app.UseAuthorization();
// ���ÿ���
app.UseCors(c => c.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());

app.MapControllers();
//ע��consul����
RegisterConsul();

app.Run();